<!--Map-->
<template>
  <a-layout-sider width="260px" v-if="$store.state.configPanalStatus.left">
    <left-tool-bar
      :leftComponentsList="leftComponentsList"
      @deleteLeftComponent="deleteLeftComponent"
      @changeAddComponentVisiable="changeAddComponentVisiable"
      @clearRightConfigAttribute="clearRightConfigAttribute"
    />
  </a-layout-sider>
  <!--功能折叠/展开-->
  <div
    class="leftIcon"
    :style="{
      left: $store.state.configPanalStatus.left ? '260px' : '0px',
    }"
    @click="changeLeftLayoutSider"
  >
    <left-outlined v-if="$store.state.configPanalStatus.left" />
    <right-outlined v-else />
  </div>
  <a-layout-content>
    <div
      class="gaodeMap"
      @mousedown="changeMouseStatus(1, $event)"
      @mouseup="changeMouseStatus(0, $event)"
      @mousewheel="mouseWheel"
      ref="vueAmap"
      id="vueAmap"
    >
      <el-amap
        :viewMode="aMapData.viewMode"
        :center="aMapData.center"
        :pitch="aMapData.pitch"
        :showIndoorMap="aMapData.showIndoorMap"
        :zoom="aMapData.zoom"
        :doubleClickZoom="aMapData.doubleClickZoom"
        :jogEnable="aMapData.jogEnable"
        :animateEnable="aMapData.animateEnable"
        :dragEnable="aMapData.dragEnable"
        :scrollWheel="aMapData.scrollWheel"
        :showLabel="aMapData.showLabel"
        :mapStyle="aMapData.mapStyle"
        :keyboardEnable="aMapData.keyboardEnable"
        :showBuildingBlock="aMapData.showBuildingBlock"
        :terrain="aMapData.terrain"
        :mask="aMapData.mask"
        :defaultCursor="aMapData.defaultCursor"
        :WebGLParams="aMapData.WebGLParams"
        @dblclick="dblclick"
        @init="initMap"
        @complete="completeMap"
        @mousemove="mousemove"
        @click="clickMap"
      >
        <!--地图控件-->
        <map-controls-components
          v-if="aMapData.tools"
          :componentLists="aMapData.tools"
          @parseFun="parseFun"
        />
        <!--线图层-->
        <polyline-components
          :polylineComponents="mapComponents.normalLayer.polylineComponents"
          ref="polylineComponents"
        />
        <!--marker层-->
        <marker-components
          :markerComponents="mapComponents.normalLayer.markerComponents"
        />
        <!--3D建筑物模块-->
        <el-amap-layer-buildings
          :visible="mapComponents.normalLayer.elAmapLayerBuildings.visible"
          :styleOpts="mapComponents.normalLayer.elAmapLayerBuildings.styleOpts"
        />
        <!--鼠标工具层-->
        <template
          v-if="$store.state.currentSelectMapToolBar.createType == 'mouseTools'"
        >
          <el-amap-mouse-tool
            :type="$store.state.currentSelectMapToolBar.id"
            :auto-clear="true"
            @draw="drawPolygon"
          />
        </template>
        <!--loca层-->
        <el-amap-loca @init="initElMapLoca" ref="amapLoca">
          <!--绘制组件-->
          <pulseLineComponents
            v-if="mapComponents.localLayer.pulseLineLayoutComponents"
            :pulseLineLayoutComponents="
              mapComponents.localLayer.pulseLineLayoutComponents
            "
            @clickPulseLine="clickPulseLine"
            ref="pulseLineLayoutComponents"
          />
          <!--拖拽贴图组件-->
          <scatterLayerComponents
            v-if="mapComponents.localLayer.scatterLayerComponents"
            :scatterLayerComponents="
              mapComponents.localLayer.scatterLayerComponents
            "
            ref="scatterLayerComponents"
          />
          <!--标注层-->
          <z-marker-layer-components
            v-if="mapComponents.localLayer.zMarkerLayerComponents"
            :zMarkerLayerComponents="
              mapComponents.localLayer.zMarkerLayerComponents
            "
            ref="zMarkerLayerComponents"
          />
          <!--面图层-->
          <polygon-components
            v-if="mapComponents.localLayer.polygonComponents"
            :polygonComponents="mapComponents.localLayer.polygonComponents"
            ref="polygonComponents"
          />
        </el-amap-loca>
        <!--右键操作-->
        <ul
          ref="contextMenuRef"
          class="contextMenu"
          v-show="displayContextmenu"
        >
          <li
            v-for="(item, index) in contextmenuData"
            :key="index"
            @click="rightMenuEvent(item)"
          >
            <p :class="item.enable ? '' : 'disabled'">
              {{ item.name }}
              <span class="shortcut">{{ item.hotkey }}</span>
            </p>
          </li>
        </ul>
      </el-amap>
    </div>
    <!-- 地图选择 -->
    <select-map-location
      :mapStyle="aMapData.mapStyle"
      :visibleSelectMapLocation="visibleSelectMapLocation"
      @showSelectMapLocation="showSelectMapLocation(false)"
      @confirmLocation="confirmLocation"
    />
  </a-layout-content>
  <!--右侧菜单配置-->
  <a-layout-sider
    class="mapSlide"
    width="270px"
    v-if="$store.state.configPanalStatus.right"
  >
    <a-map-right-config
      :formData="formData"
      :aMapData="aMapData"
      :zMarkerLayerComponents="mapComponents.localLayer.zMarkerLayerComponents"
      :viewControlConfig="mapComponents.normalLayer.viewControlConfig"
      @showSelectMapLocation="showSelectMapLocation"
      @removeMapMask="removeMapMask"
    />
  </a-layout-sider>
  <!--功能折叠/展开-->
  <div
    class="rightIcon"
    :style="{
      right: $store.state.configPanalStatus.right ? '270px' : '0px',
    }"
    @click="
      $store.setconfigPanalStatusVal(
        !$store.state.configPanalStatus.right,
        'right'
      )
    "
  >
    <right-outlined v-if="$store.state.configPanalStatus.right" />
    <left-outlined v-else />
  </div>
  <!-- add components -->
  <add-components
    :addComponentVisible="addComponentVisible"
    :getPopupContainer="getPopupContainer"
    @confirmAddSvg="confirmAddSvg"
    @cancel="changeAddComponentVisiable"
  />
  <!--add editTemplate-->
  <submit-template
    v-if="submitTemplateVisiable"
    :submitTemplateVisiable="submitTemplateVisiable"
    :submitTemplateParams="submitTemplateParams"
    @createTemplate="createTemplate(submitTemplateParams)"
    @cancelSubmitTemplate="changeSubmitTemplateVisiable"
  />
</template>
<script>
import aMapRightConfig from '@/components/mapComponents/aMapRightConfig.vue';
import selectMapLocation from '@/common/selectMapLocation.vue';
import mapControlsComponents from '@/components/mapComponents/recursiveComponent/mapControlsComponents.vue';
import scatterLayerComponents from '@/components/mapComponents/dragMapComponent/scatterLayerComponents.vue';
import pulseLineComponents from '@/components/mapComponents/drawMapComponent/pulseLineComponents.vue';
import leftToolBar from '@/components/mapComponents/leftToolBar.vue';
import addComponents from '@/components/mapComponents/addComponents.vue';
import submitTemplate from '@/common/submitTemplate.vue';
import zMarkerLayerComponents from '@/components/mapComponents/dragMapComponent/zMarkLayerComponents.vue';
import polygonComponents from '@/components/mapComponents/fenceComponent/polygonComponents.vue';
import polylineComponents from '@/components/mapComponents/polylineComponent/polylineComponents.vue';
import markerComponents from '@/components/mapComponents/markerComponent/markerComponents.vue';
import {
  DoubleLeftOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {
  deleteComponent,
  listComponent,
  addComponent,
  userUploader,
} from '@/network/api/index';
import {
  pixelSwapToLanLat,
  Insertion,
  binaryTreeFun,
  convertCanvasToImage,
  queryMapComponentFeature,
} from '@/util/index';
import { Screenshot } from '@amap/screenshot';
export default {
  components: {
    DoubleLeftOutlined,
    aMapRightConfig,
    selectMapLocation,
    mapControlsComponents,
    scatterLayerComponents,
    pulseLineComponents,
    zMarkerLayerComponents,
    leftToolBar,
    LeftOutlined,
    RightOutlined,
    addComponents,
    submitTemplate,
    polygonComponents,
    polylineComponents,
    markerComponents,
  },
  data() {
    return {
      map: null,
      mouseStatus: 0, //0:抬起 1:按下
      visibleSelectMapLocation: false,
      displayContextmenu: false,
      cancelMapClickEvent: false, //是否取消点击地图的冒泡事件
      aMapData: {
        viewMode: '3D',
        zoom: 18,
        pitch: 60,
        center: [113.386974, 23.171124],
        // center: [113.880875, 22.798142],
        visible: true,
        defaultCursor: 'pointer',
        showIndoorMap: true,
        doubleClickZoom: false,
        jogEnable: false,
        animateEnable: false,
        dragEnable: true,
        scrollWheel: true,
        showLabel: false, //是否开启文字
        keyboardEnable: true,
        showBuildingBlock: false, //默认全部关闭3d建筑物，使用组件建筑物
        terrain: false, //是否开启地形
        mask: null, //掩模路径
        mapStyle: 'amap://styles/9c798d685f08c78de10a8dc2c1483155', //默认地图样式
        //截图参数
        WebGLParams: {
          preserveDrawingBuffer: true,
        },
        //工具
        tools: [
          {
            text: '定位',
            name: 'div',
            class: ['getLocation'],
            visible: true,
            event: {
              funType: 'click',
              funName: 'getLocation',
            },
            childrenContainer: [
              {
                text: '定位图标',
                name: 'aim-outlined',
                visible: true,
                class: ['locationIcon'],
                event: {
                  funType: '',
                  funName: '',
                },
              },
            ],
          },
          {
            text: '比例尺',
            name: 'el-amap-control-scale',
            visible: true,
            event: {
              funType: '',
              funName: '',
            },
          },
          {
            text: '地图类型',
            name: 'el-amap-control-map-type',
            visible: true,
            event: {
              funType: '',
              funName: '',
            },
          },
          {
            text: '地图控制',
            name: 'el-amap-control-control-bar',
            visible: true,
            event: {
              funType: '',
              funName: '',
            },
          },
          // {
          //   text: '鹰眼控件',
          //   name: 'el-amap-control-hawk-eye',
          //   visible: false,
          //   mapStyle: 'amap://styles/9c798d685f08c78de10a8dc2c1483155',
          //   event: {
          //     funType: '',
          //     funName: '',
          //   },
          // },
        ],
      },
      formData: {
        address: '',
        longitude: '',
        latitude: '',
        selectMapComponent: {}, //当前选中地图组件
      },
      submitTemplateParams: {
        templateName: '',
        remark: '',
        backgroundImg: '', //背景图
        previewImg: '', //自动截屏预览图片
        components: [], //组件列表
        waterTemplateId: '',
      },
      /**地图拖拽组件，后续增加组件和属性类型，请参考官网可支持的拖拽组件类型
       */
      mapComponents: {
        //普通图层
        normalLayer: {
          markerComponents: [], //marker层标注
          //3D建筑物
          elAmapLayerBuildings: {
            styleOpts: {
              hideWithoutStyle: true, //是否隐藏围栏之外的楼块
              areas: null, //围栏信息数组
            },
            zIndex: 12,
            opacity: 1, //透明度
            visible: true, //全部区域的显示状态
          },
          polylineComponents: [], //描边线
          //镜头动画
          viewControlConfig: {
            status: true, //镜头动画状态
            isCycle: false, //是否循环
            interval: 1000, //循环间隔
            list: [], //动画数组
            activeAnimation: -1, //当前执行的动画
          },
        },
        //local图层
        localLayer: {
          scatterLayerComponents: [], //贴图层组件
          pulseLineLayoutComponents: [], //轨迹线层组件
          zMarkerLayerComponents: [], //垂直mark
          polygonComponents: [], //面图层
        },
      },
      //鼠标右键
      contextmenuData: [
        {
          name: '复制',
          type: 'copy',
          hotkey: 'Ctrl+C',
          enable: true,
        },
        {
          name: '删除',
          type: 'delete',
          hotkey: 'Delete',
          enable: false,
        },
        {
          name: '置于上一层',
          type: 'nextTop',
          hotkey: 'Ctrl+↑',
          enable: true,
        },
        {
          name: '置于下一层',
          hotkey: 'Ctrl+↓',
          type: 'nextBottom',
          enable: true,
        },
      ],
      localRef: '', //loca层ref
      leftComponentsList: [],
      addComponentVisible: false,
      submitTemplateVisiable: false,
    };
  },
  provide() {
    return {
      getMap: () => this.map,
      getLocaRef: () => this.locaRef,
      getAmapDataCenter: () => this.aMapData.center.toString(),
    };
  },
  inject: ['getScreenFullNode'],
  computed: {
    getPopupContainer() {
      return this.getScreenFullNode();
    },
  },
  created() {
    let _this = this;
    //当前页面监视键盘输入
    document.onkeydown = function (e) {
      //获取当前选中组件
      let selectMapComponent = _this.formData.selectMapComponent;
      //面图层不做快捷键好移动处理
      if (JSON.stringify(selectMapComponent) == '{}' || !selectMapComponent) {
        _this.aMapData.keyboardEnable = true;
        //还原键盘控制屏幕
        if (!e.preventDefault) {
          e.returnValue = true;
        }
        return;
      }
      // //取消键盘控制屏幕
      // if (e.preventDefault) {
      //   e.preventDefault();
      // } else {
      //   e.returnValue = false;
      // }
      //取消地图键盘控制
      _this.aMapData.keyboardEnable = false;
      //事件对象兼容
      let e1 = e || window.event || arguments.callee.caller.arguments[0];
      const selectComponent = _this.formData.selectMapComponent;
      //ctrl  c
      if (e1 && e1.ctrlKey && e1.keyCode == 67) {
        e.preventDefault();
        _this.rightMenuEvent({ type: 'copy', enable: true });
      }
      //deleted
      else if (e1 && e1.keyCode == 46) {
        e.preventDefault();
        _this.rightMenuEvent({ type: 'delete', enable: true });
      }
      //左箭头
      else if (e1 && e1.keyCode == 37) {
        _this.formData.selectMapComponent.x--;
        _this[`change${selectComponent.type}Pixel`](0);
      }
      //右箭头
      else if (e1 && e1.keyCode == 39) {
        _this.formData.selectMapComponent.x++;
        _this[`change${selectComponent.type}Pixel`](0);
      }
      //上箭头
      else if (e1 && e1.keyCode == 38) {
        _this.formData.selectMapComponent.y--;
        _this[`change${selectComponent.type}Pixel`](1);
      }
      //下箭头
      else if (e1 && e1.keyCode == 40) {
        _this.formData.selectMapComponent.y++;
        _this[`change${selectComponent.type}Pixel`](1);
      }
      //上移一层
      else if (e1 && e1.ctrlKey && e1.key == 'ArrowUp') {
        e.preventDefault();
        _this.rightMenuEvent({ type: 'nextTop', enable: true });
      }
      //下移一层
      else if (e1 && e1.ctrlKey && e1.key == 'ArrowDown') {
        e.preventDefault();
        _this.rightMenuEvent({ type: 'nextBottom', enable: true });
      }
    };
    this.getLeftComponents();
  },
  methods: {
    //开启loca层中的动画
    initElMapLoca(elMapLoca) {
      elMapLoca.animate.start();
    },

    //移除掩模
    removeMapMask() {
      setTimeout(() => {
        this.aMapData.mask = null;
        console.log(this.aMapData.mask);
      }, 500);
    },
    /**
     * 绘制面
     * @param {*} mask 统一为处理后的坐标数组
     */
    addMapPolygon(mask, componentsId) {
      const len = this.mapComponents.localLayer.polygonComponents.length;
      //创建geometry格式
      let polygonItem = {
        type: 'polygonComponents',
        visible: true,
        depth: false,
        cullface: 'none',
        blockHide: true,
        // acceptLight: true,
        zIndex: 12 + len,
        buildingIndex: len, //索引关联区域建筑物
        opacity: 1,
        sourceData: {
          type: 'FeatureCollection',
          features: [
            {
              type: 'Feature',
              properties: {
                name: '区域' + len,
                componentsId: componentsId,
                clickType: 'clickPolygon',
                type: 'polygonComponents',
              },
              geometry: {
                type: 'Polygon',
                coordinates: [mask],
              },
            },
          ],
        },
        layerStyle: {
          topColor: 'rgba(255,255,255,0)',
          bottomColor: 'rgba(255,255,255,0)',
          sideTopColor: 'rgba(0,255,255,0)',
          sideBottomColor: '#00C6DA',
          height: 100,
          texture: null,
          textureSize: [20, 3],
          altitude: 0,
        },
      };
      this.addMaskBuildings(
        mask,
        polygonItem.sourceData.features[0].properties.componentsId
      ); //增加掩模建筑物
      this.mapComponents.localLayer.polygonComponents.push(polygonItem); //增加面图层
    },
    /**
     * 增加3d建筑物掩模
     * @param {*} mask
     * @param {*} componentsId
     */
    addMaskBuildings(mask, componentsId) {
      let buildingsStylAreas =
        this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas;
      //掩模3D建筑物
      let buildingsItem = {
        componentsId: componentsId,
        visible: true,
        rejectTexture: false, //是否隐藏自定义地图纹理
        path: [mask], //经纬列表
        color1: '#1E2B3E', //区域内楼快顶部颜色，默认为导航蓝样式
        color2: '#010108', //区域内楼快侧面颜色，默认导航蓝样式
      };
      if (buildingsStylAreas != null) {
        this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas.push(
          buildingsItem
        );
      } else {
        this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas = [
          buildingsItem,
        ];
      }
    },
    //创建面图层
    drawPolygon(res, e) {
      res.push(res[0]); //闭合面
      //添加面
      this.addMapPolygon(res);
    },
    /**
     * 通过经度查找关联的面
     * @param {*} startCoordinates
     * @param {*} endCoordinates
     */
    searchPolygon(startCoordinates, endCoordinates) {
      return this.mapComponents.localLayer.polygonComponents.filter(
        (polygonItem, index) => {
          const coordinates =
            polygonItem.sourceData.features[0].geometry.coordinates[0];
          if (
            coordinates[0].join() == startCoordinates &&
            coordinates[coordinates.length - 1].join() == endCoordinates
          ) {
            polygonItem.arrIndex = index;
            return polygonItem;
          }
        }
      )[0];
    },
    /**
     * 通过componentsId 查询区域绘制线
     * @param {*} componentsId
     */
    searchPolyline(componentsId) {
      return this.mapComponents.normalLayer.polylineComponents.filter(
        (polylineItem, index) => {
          if (polylineItem.extData.componentsId == componentsId) {
            polylineItem.arrIndex = index;
            return polylineItem;
          }
        }
      )[0];
    },
    /**
     * 通过componentsId 查询区域3D建筑掩模
     * @param {*} componentsId
     */
    searchBuilding(componentsId) {
      return this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas.filter(
        (buildingItem, index) => {
          if (buildingItem.componentsId == componentsId) {
            buildingItem.arrIndex = index;
            return buildingItem;
          }
        }
      )[0];
    },
    createTemplate() {
      this.getAMapUrl(this.map).then((res) => {
        this.submitTemplateParams.previewImg = res.filePath;
        console.log(this.mapComponents);
      });
      // Object.assign(this.submitTemplateParams, val);
      // this.submitTemplateParams.components = JSON.parse(
      //   JSON.stringify(this.templateSvgLists)
      // );
      // if (!this.submitTemplateParams.components.length) {
      //   message.error('模板内容不能为空哦~');
      // } else {
      //   //获取编辑的图片链接
      //   this.selectTemplateSvg = {};
      //   this.getImgUrl(this.$refs.svgContainer).then((url) => {
      //     this.submitTemplateParams.previewImg = url; //自动截屏预览图片
      //     this.submitTemplateParams.backgroundImg =
      //       this.$store.state.BGIMG.BASE64DATA; //背景图片
      //     //translate to string
      //     this.submitTemplateParams.components
      //       ? this.submitTemplateParams.components.forEach((item) => {
      //           item.defaultAttr = JSON.stringify(item.defaultAttr);
      //         })
      //       : '';
      //     this.submitTemplateParams.waterTemplateId = this.templateId
      //       ? this.templateId
      //       : '';
      //     this.$httpRequest(
      //       addWaterTemplate,
      //       this.submitTemplateParams,
      //       'post'
      //     ).then((res) => {
      //       this.templateId = res.data;
      //       message.success('保存成功~');
      //       //保存模板关联的分组信息
      //       this.$refs.rightToobar.submitGroup(this.templateId);
      //       this.submitTemplateParams = {};
      //       this.selectTemplateSvg = this.templateSvgLists[0];
      //     });
      //   });
      // }
    },
    /**
     * 获取地图截图
     * @param {*} map  地图对象
     */
    getAMapUrl(map) {
      return new Promise((resolve, reject) => {
        //插件请参考官网参数配置
        const screenshot = new Screenshot(map);
        screenshot.toDataURL().then((imageBase64) => {
          //上传图片
          this.$httpRequest(
            userUploader,
            convertCanvasToImage(
              imageBase64,
              this.submitTemplateParams.templateName
            ),
            'post',
            'multipart/form-data'
          )
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        });
      });
    },
    changeSubmitTemplateVisiable(val) {
      this.submitTemplateVisiable = val;
    },
    confirmAddSvg(val) {
      this.$httpRequest(
        addComponent,
        {
          createType: val.createType,
          defaultAttr:
            val.imgType == 'img' ? null : JSON.stringify(val.defaultAttr),
          imgType: val.imgType,
          priviewImg: val.priviewImg,
          template: val.template,
          title: val.title,
          type: val.type,
        },
        'post'
      ).then(() => {
        message.success('添加成功~');
        this.addComponentVisible = false;
        this.getLeftComponents();
      });
    },
    dblclick() {
      //取消线绘制状态
      if (JSON.stringify(this.formData.selectMapComponent) != '{}') {
        if (
          this.formData.selectMapComponent.type == 'pulseLineLayoutComponents'
        ) {
          console.log('取消编辑');
          //取消选中可移动的偏移坐标
          var pulseLineComponent = this.formData.selectMapComponent;
          const len =
            pulseLineComponent.sourceData.features[0].geometry.coordinates
              .length;
          //移除节点
          pulseLineComponent.sourceData.features[0].geometry.coordinates.splice(
            len - 1,
            1
          );
          //获取终点坐标
          const pixelVal = pixelSwapToLanLat(
            pulseLineComponent.sourceData.features[0].geometry.coordinates[
              len - 2
            ][0],
            pulseLineComponent.sourceData.features[0].geometry.coordinates[
              len - 2
            ][1],
            this.map,
            'px'
          );
          pulseLineComponent.x = Number(pixelVal.x.toFixed());
          pulseLineComponent.y = Number(pixelVal.y.toFixed());
          this.formData.selectMapComponent = {};
          // this.$store.clearCurrentlySelectedMapToolBarAction();
        }
        return;
      }
      //面绘制不做收起
      if (this.$store.state.currentSelectMapToolBar.createType == 'mouseTools')
        return;
      //改变当前工具栏状态
      this.$store.setconfigPanalStatusVal(
        !this.$store.state.configPanalStatus.left
      );
      this.$store.setconfigPanalStatusVal(
        !this.$store.state.configPanalStatus.right,
        'right'
      );
      this.getLeftComponents();
    },
    changeLeftLayoutSider() {
      this.$store.setconfigPanalStatusVal(
        !this.$store.state.configPanalStatus.left
      );
      this.$store.state.configPanalStatus.left ? this.getLeftComponents() : '';
    },
    changeAddComponentVisiable(val) {
      this.addComponentVisible = val;
    },
    deleteLeftComponent(id) {
      this.$httpRequest(deleteComponent, { componentId: id }, 'delete').then(
        () => {
          message.success('删除操作成功~');
          this.getLeftComponents();
        }
      );
    },
    getLeftComponents() {
      //请求接口获取组件
      this.$httpRequest(listComponent).then((res) => {
        res?.data
          ? res.data.forEach((item) => {
              item.defaultAttr = JSON.parse(item.defaultAttr);
            })
          : '';
        this.leftComponentsList = res?.data ? res.data : [];
      });
    },
    //改变当前贴点像素
    changescatterLayerComponentsPixel(index) {
      let selectScatterComponent = this.formData.selectMapComponent;
      const dict = {
        0: 'lng',
        1: 'lat',
      };
      selectScatterComponent.sourceData.features[0].geometry.coordinates[
        index
      ] = pixelSwapToLanLat(
        selectScatterComponent.x,
        selectScatterComponent.y,
        this.map
      )[dict[index]];
    },
    //改变当前轨迹线像素
    changepulseLineLayoutComponentsPixel(index) {
      let selectScatterComponent = this.formData.selectMapComponent;
      const dict = {
        0: 'lng',
        1: 'lat',
      };
      selectScatterComponent.sourceData.features[0].geometry.coordinates[
        selectScatterComponent.index
      ][index] = pixelSwapToLanLat(
        selectScatterComponent.x,
        selectScatterComponent.y,
        this.map
      )[dict[index]];
    },
    changeMouseStatus(status, e) {
      //鼠标右键不能拖拽
      if (e.buttons != 2) {
        this.mouseStatus = status;
        //鼠标抬起，恢复地图点击事件
        status == 0 ? (this.cancelMapClickEvent = false) : '';
      } else {
        if (JSON.stringify(this.formData.selectMapComponent) != '{}') {
          const contextMenuRef = this.$refs.contextMenuRef;
          this.displayContextmenu = true;
          contextMenuRef.style.left = e.offsetX + 'px';
          contextMenuRef.style.top = e.offsetY + 'px';
          //初始化
          this.contextmenuData.map((m) => (m.enable = true));
          const componentType = this.formData.selectMapComponent.type;
          //根据组件处理不同的操作
          this[`${componentType}ContextMenuStatus`](componentType);
        }
      }
    },
    //贴图组件右键可操作状态
    scatterLayerComponentsContextMenuStatus(componentType) {
      //判断当前选中组件的index
      if (this.mapComponents.localLayer[componentType].length == 1) {
        //禁用上移
        this.contextmenuData[2].enable = false;
        //禁用下移
        this.contextmenuData[3].enable = false;
      } else if (this.formData.selectMapComponent.zIndex == 12) {
        //禁用下移
        this.contextmenuData[3].enable = false;
      } else if (
        this.mapComponents.localLayer[componentType].zIndex - 12 ===
        this.mapComponents.localLayer[componentType].length
      ) {
        //禁用上移
        this.contextmenuData[2].enable = false;
      }
    },
    //轨迹线右键可操作状态
    pulseLineLayoutComponentsContextMenuStatus(componentType) {
      //禁用复制
      this.contextmenuData[0].enable = false; //考虑到线的复杂性，禁用复杂
      //判断当前选中组件的index
      if (this.mapComponents.localLayer[componentType].length == 1) {
        //禁用上移
        this.contextmenuData[2].enable = false;
        //禁用下移
        this.contextmenuData[3].enable = false;
      } else if (this.formData.selectMapComponent.zIndex == 9) {
        //禁用下移
        this.contextmenuData[3].enable = false;
      } else if (
        this.mapComponents.localLayer[componentType].zIndex - 12 ===
        this.mapComponents.localLayer[componentType].length
      ) {
        //禁用上移
        this.contextmenuData[2].enable = false;
      }
    },
    //面图层右键可操作状态
    polygonComponentsContextMenuStatus(componentType) {
      //考虑到面的复杂性,除了删除操作，其他禁用
      this.contextmenuData.forEach((item, index) => {
        index != 1 ? (item.enable = false) : '';
      });
    },
    /**
     *
     * @param {*} formData
     */
    confirmLocation(formData) {
      this.$nextTick(() => {
        const componentsId = this.$UCore.GenUUid();
        this.gaodeMapformData = Object.assign(this.formData, formData);
        this.aMapData.center = [formData.longitude, formData.latitude];
        //增加mark
        this.mapComponents.normalLayer.markerComponents = [
          {
            visible: true,
            position: [formData.longitude, formData.latitude],
            angle: 0,
            title: formData.address,
            // size:[10,20],
            // icon: 'https://a.amap.com/Loca/static/loca-v2/demos/images/track_marker.png',
          },
        ];
        // this.newMark([formData.longitude, formData.latitude]);
        // 宏任务增加区域掩模
        setTimeout(() => {
          // if (this.aMapData.mask != null) {
          //   //处理多层区域不显示问题
          //   let mask = JSON.parse(JSON.stringify(this.aMapData.mask));
          //   this.aMapData.mask = null;
          //   this.aMapData.mask = mask;
          //   this.aMapData.mask.push(formData.mask);
          // } else {
          if (this.aMapData.mask) {
            const coordinates = this.aMapData.mask[0][0];
            const oldPolygon = this.searchPolygon(
              coordinates[0].join(),
              coordinates[coordinates.length - 1].join()
            );
            const oldPolyline = this.searchPolyline(
              oldPolygon.sourceData.features[0].properties.componentsId
            );
            const oldBuildings = this.searchBuilding(
              oldPolygon.sourceData.features[0].properties.componentsId
            );
            this.mapComponents.normalLayer.polylineComponents.splice(
              oldPolyline.arrIndex,
              1
            ); //删除上一次绘制的区域线
            this.mapComponents.localLayer.polygonComponents.splice(
              oldPolygon.arrIndex,
              1
            ); //删除上一次选择的区域面
            this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas.splice(
              oldBuildings.arrIndex,
              1
            ); //删除建筑掩模
          }
          this.aMapData.mask = [formData.mask]; //目前只做一个掩模，不再考虑多个掩模问题
          // }
        }, 500);
        //描边-----本可以做成单独属性配置，懒的做了，后续自行增加
        this.mapComponents.normalLayer.polylineComponents.push({
          visible: true,
          path: formData.mask,
          lineJoin: 'round',
          strokeColor: '#0099ff',
          strokeWeight: 6,
          isOutline: true,
          geodesic: true,
          extData: {
            componentsId: componentsId,
          },
        });
        this.addMapPolygon(formData.mask[0], componentsId); //面
        this.showSelectMapLocation(false);
      });
    },
    getLocation() {
      this.formData.longitude && this.formData.latitude
        ? this.newMark([this.formData.longitude, this.formData.latitude])
        : message.warning('当前暂无选中坐标点哦~');
    },
    //初始化地图，拖拽组件事件监听
    initMap(map) {
      const _this = this;
      _this.map = map;
      //拖拽
      _this.$nextTick(() => {
        const vueAmap = _this.$refs.vueAmap;
        vueAmap.addEventListener(
          'dragover',
          function (e) {
            e.preventDefault();
          },
          false
        );
        vueAmap.addEventListener('drop', function (e) {
          e.preventDefault();
          if (
            _this.$store.state.currentSelectMapToolBar.createType !=
            'mapDraggable'
          )
            return;
          const aMapLocation = _this.getCoordinates(e);
          const length =
            _this.mapComponents.localLayer[
              _this.$store.state.currentSelectMapToolBar.componentType
            ].length;
          //官方组件参数配置，后续增加自行参考官网
          var draggableItem = {
            type: 'scatterLayerComponents',
            //统一使用px记录坐标点
            x: e.offsetX,
            y: e.offsetY,
            visible: true,
            opacity: 1,
            isShowMark: false, //默认不显示mark组件
            zIndex: length + 12,
            sourceData: _this.$store.state.currentSelectMapToolBar.sourceData,
            layerStyle: _this.$store.state.currentSelectMapToolBar.layerStyle,
          };
          Object.assign(draggableItem.sourceData, {
            type: 'FeatureCollection',
            features: [
              {
                type: 'Feature',
                //经纬度
                geometry: {
                  type: _this.$store.state.currentSelectMapToolBar.geometryType, //类型名称
                  coordinates: [aMapLocation.lng, aMapLocation.lat],
                },
                //自定义属性
                properties: {
                  name:
                    _this.$store.state.currentSelectMapToolBar.name + length,
                  type: 'scatterLayerComponents', //组件类型
                  clickType: 'clickScatterLayer', //点击地图事件名称
                  componentsId: _this.$UCore.GenUUid(),
                },
              },
            ],
          });
          Object.assign(draggableItem.layerStyle, {
            unit: 'meter',
            rotation: 0,
            altitude: 0,
            size: [5, 5],
            borderWidth: 2.5,
            color: '#fe321e',
            borderColor: '#fc8f72',
            duration: 0,
            animate: false,
          });
          _this.mapComponents.localLayer[
            _this.$store.state.currentSelectMapToolBar.componentType
          ].push(draggableItem);
          _this.$store.clearCurrentlySelectedMapToolBarAction();
          _this.formData.selectMapComponent = draggableItem;
          _this.aMapData.keyboardEnable = false; //取消地图键盘事件
        });
      });
    },
    completeMap() {
      this.locaRef = this.$refs.amapLoca.$$getInstance();
      // this.visibleSelectMapLocation = !this.visibleSelectMapLocation;
    },
    testDirection() {
      var aMapData = this.aMapData;
      var map = this.map;
      var loca = this.$refs.amapLoca.$$getInstance();
      //环境光，对于可以接受光照的图层（PolygonLayer 等）会增加环境光的影响。环境光只能有一个，多余的会被忽略。
      loca.ambLight = {
        intensity: 2.2,
        color: '#babedc',
      };
      //平行光，对于可以接受光照的图层（PolygonLayer 等）会增加平行光的影响。平行光一般用来模拟太阳的光照。 它的方向由 position 射向 target。position和target的坐标是一个位置加 z 值（单位米）高度决定。
      loca.dirLight = {
        intensity: 0.46,
        color: '#d4d4d4',
        target: [0, 0, 0],
        position: [0, -1, 1],
      };
      //点光，对于可以接受光照的图层（PolygonLayer 等）会增加点光的影响。点光源通常用来突出展示场景中的某些物体。
      loca.pointLight = {
        color: 'rgb(15,19,40)',
        position: aMapData.center,
        intensity: 25,
        // 距离表示从光源到光照强度为 0 的位置，0 就是光不会消失。
        distance: 3900,
      };
      var geo = new Loca.GeoJSONSource({
        url: 'https://a.amap.com/Loca/static/loca-v2/demos/mock_data/sh_building_center.json',
      });

      var pl = (window.pl = new Loca.PolygonLayer({
        zIndex: 120,
        shininess: 10,
        hasSide: true,
        cullface: 'back',
        depth: true,
      }));

      pl.setSource(geo);

      pl.setStyle({
        topColor: '#111',
        height: function (index, feature) {
          return feature.properties.h;
        },
        textureSize: [1000, 820],
        texture:
          'https://a.amap.com/Loca/static/loca-v2/demos/images/windows.jpg',
      });
      pl.setLoca(loca);
      setTimeout(animate, 2000);

      function animate() {
        var speed = 1;
        // 镜头动画
        map.setZoom(11.8, true);
        //设置地图俯仰角 (角度,是否过渡,动画时长)
        map.setPitch(0, true);
        map.setCenter(aMapData.center, true);
        //设置地图顺时针旋转角度, 旋转原点为地图容器中心点, 取值范围: 任意数字
        map.setRotation(1, true);
        pl.hide(1000);

        // 下钻
        loca.viewControl.addAnimates(function () {
          setTimeout(function () {
            pl.show(2000);
          }, 3000);
          setTimeout(() => {
            // loca.viewControl.pauseAnimate();
            setTimeout(() => {
              loca.viewControl.resumeAnimate();
              setTimeout(() => {
                // loca.viewControl.clearAnimates();
                // loca.viewControl.resumeAnimate();
              }, 2000);
            }, 2000);
          }, 3000);
          loca.viewControl.addAnimates([], function () {
            pl.hide(1000);
            setTimeout(animate, 2000);
            console.log('结束');
          });
        });
      }
    },
    showSelectMapLocation(val) {
      this.visibleSelectMapLocation = val;
    },
    /**
     * 控件回调函数
     * @param {*} val e:原生回调参数 funName:点击函数名 type:组件类型
     */
    parseFun(val) {
      switch (val.type) {
        //地图控件函数
        case 'dynamic':
          this[val.funName](val.e);
          break;
      }
    },
    //清空当前选择属性
    clearRightConfigAttribute() {
      this.formData.selectMapComponent = {};
    },
    //点击地图
    clickMap(e) {
      //点击地图查询当前鼠标点是否存在local层
      e
        ? queryMapComponentFeature(
            [e.pixel.x, e.pixel.y],
            this.mapComponents.localLayer,
            this,
            e
          ).then((res) => {
            if (JSON.stringify(this.formData.selectMapComponent) != '{}')
              return;
            //点击相关层的组件
            this[
              res?.properties?.clickType
                ? res.properties.clickType
                : 'undefinedFun'
            ](res, e);
          })
        : '';
      if (this.$store.state.currentSelectMapToolBar?.createType != 'mapDraw') {
        if (!this.cancelMapClickEvent) {
          this.formData.selectMapComponent = {};
          this.aMapData.dragEnable = !this.aMapData.dragEnable;
          this.displayContextmenu = false;
          this.aMapData.keyboardEnable = !this.aMapData.keyboardEnable;
          return;
        }
      } else {
        const pixelVal = e.originEvent; //像素
        this.$nextTick(() => {
          //当前线条增加节点
          if (JSON.stringify(this.formData.selectMapComponent) != '{}') {
            console.log('增加节点');
            var pulseLineComponent = this.formData.selectMapComponent;
            const len =
              this.formData.selectMapComponent.sourceData.features[0].geometry
                .coordinates.length;
            const clickCoordinates = this.getCoordinates(e.originEvent);

            const moveCoordinates = this.getCoordinates({
              pixel: { x: pixelVal.offsetX + 0.5, y: pixelVal.offsetY + 0.5 },
            });
            //节点和节点坐标
            pulseLineComponent.x = pixelVal.offsetX;
            pulseLineComponent.y = pixelVal.offsetY;
            //增加节点
            pulseLineComponent.sourceData.features[0].geometry.coordinates[
              len - 1
            ] = [clickCoordinates.lng, clickCoordinates.lat];
            //增加一个可移动节点(为选定节点偏移0.5像素)
            pulseLineComponent.sourceData.features[0].geometry.coordinates[
              len
            ] = [moveCoordinates.lng, moveCoordinates.lat];
          } else {
            //绘制线
            console.log('创建线');
            this.formData.selectMapComponent = {};
            const selectComponent = this.$store.state.currentSelectMapToolBar;
            let len =
              this.mapComponents.localLayer[selectComponent.componentType]
                .length;
            const startCoordinate = this.getCoordinates(e.originEvent);
            //默认终点偏移原点的0.5像素
            const lastCoordinate = this.getCoordinates({
              pixel: { x: pixelVal.offsetX + 0.5, y: pixelVal.offsetY + 0.5 },
            });
            var pulseLineComponent = {
              type: selectComponent.componentType,
              visible: true, //是否可见
              opacity: 1, //透明度
              x: pixelVal.offsetX,
              y: pixelVal.offsetY,
              isShowMark: false, //默认不显示mark组件
              zIndex: 9 + len, //默认层级
              index: 0,
              sourceData: {
                type: 'FeatureCollection',
                features: [
                  {
                    type: 'Feature',
                    properties: {
                      name: `轨迹线${len}`,
                      componentsId: this.$UCore.GenUUid(),
                      type: selectComponent.componentType,
                      arrIndex: len ? len : 0,
                      clickType: 'clickPulseLine',
                    },
                    geometry: {
                      type: 'LineString',
                      coordinates: [
                        [startCoordinate.lng, startCoordinate.lat],
                        [lastCoordinate.lng, lastCoordinate.lat],
                      ],
                    },
                  },
                ],
              },
              layerStyle: {
                altitude: 0, //海拔高度
                lineWidth: 5, //线宽度
                headColor: '#1f87e8', //头部颜色
                trailColor: '#1f87e8', //尾部颜色
                interval: 0.5, //间隔
                animate: false, //是否开启动画
                duration: 8000, //动画时长
              },
            };
            this.mapComponents.localLayer[selectComponent.componentType].push(
              pulseLineComponent
            );
            this.formData.selectMapComponent = pulseLineComponent;
          }
        });
      }
    },
    //点击没有定义点击函数图层
    undefinedFun() {
      message.error('不要乱点哦，当前图层没有定义可操作行为~');
    },
    //点击当前贴点
    clickScatterLayer(val) {
      this.cancelMapClickEvent = true;
      if (this.cancelMapClickEvent) {
        this.formData.selectMapComponent = this.getClickComponent(
          val.properties.componentsId,
          val.properties.type
        )[0];
      }
    },
    //点击当前轨迹线
    clickPulseLine(val, e) {
      const coordinates = this.getCoordinates(e);
      this.formData.selectMapComponent = this.getClickComponent(
        val.properties.componentsId,
        val.properties.type
      )[0];
      let selectComponent = this.formData.selectMapComponent;
      //模糊匹配鼠标周围坐标点,有点菜，自行优化
      const selectLinCoordinates = this.selectLineCoordinates(
        val.coordinates,
        coordinates
      );
      if (selectLinCoordinates) {
        const lng =
          selectComponent.sourceData.features[0].geometry.coordinates[
            selectLinCoordinates.index
          ][0];
        const lat =
          selectComponent.sourceData.features[0].geometry.coordinates[
            selectLinCoordinates.index
          ][1];
        const pixel = pixelSwapToLanLat(lng, lat, this.map, 'px');
        // selectComponent.index = selectLinCoordinates.index;
        // selectComponent.arrIndex = val.properties.arrIndex;
        selectComponent.x = Number(pixel.x.toFixed());
        selectComponent.y = Number(pixel.y.toFixed());
      }
    },
    //点击当前 面图层
    clickPolygon(val, e) {
      //防止绘制线和点击面图层冲突
      if (this.$store.state.currentSelectMapToolBar.createType == 'mapDraw')
        return;
      this.clickMap();
      this.formData.selectMapComponent = this.getClickComponent(
        val.properties.componentsId,
        val.properties.type
      )[0];
      //当前区域建筑物
      this.formData.selectMapComponent.areaBuildings =
        this.mapComponents.normalLayer.elAmapLayerBuildings;
    },
    //获取鼠标移动的坐标点,e鼠标原参数
    getCoordinates(e) {
      if ((e?.pixel?.x && e?.pixel?.y) || (e.offsetX && e.offsetY)) {
        const pixelX = e?.pixel?.x || e.offsetX;
        const pixelY = e?.pixel?.y || e.offsetY;
        return pixelSwapToLanLat(pixelX, pixelY, this.map);
      }
    },
    /**
     * 模糊匹配当鼠标附近的已有的坐标点
     * @param {*} coordinatesArr 坐标数组
     * @param {*} coordinates 当前鼠标点击坐标
     * @param {*} ambiguity 模糊度
     */
    selectLineCoordinates(coordinatesArr, coordinates, ambiguity = 0) {
      try {
        let pixleArr = [];
        let sortPixleArr = [];
        coordinatesArr.forEach((item, index) => {
          const pixelItem = pixelSwapToLanLat(item[0], item[1], this.map, 'px');
          pixleArr.push({
            index: index,
            val: Number((pixelItem.x + pixelItem.y).toFixed()),
          });
        });
        const coor = pixelSwapToLanLat(
          coordinates.lng,
          coordinates.lat,
          this.map,
          'px'
        );
        sortPixleArr = Insertion(pixleArr);
        const selectCoordinates = binaryTreeFun(
          sortPixleArr,
          Number((coor.x + coor.y).toFixed())
        );
        if (selectCoordinates.val > -1) {
          throw selectCoordinates;
        }
      } catch (err) {
        return err;
      }
    },
    /**
     * 获取当前点击的组件
     * @param {*} componentsId  组件id
     * @param {*} type  组件所属类型
     */
    getClickComponent(componentsId, type) {
      return this.mapComponents.localLayer[type].filter((item, index) => {
        if (
          item.sourceData.features[0].properties.componentsId == componentsId
        ) {
          item.arrIndex = index; //记录数组下标
          return item;
        }
      });
    },
    mousemove(e) {
      this.$nextTick(() => {
        //获取移动像素 ---> 坐标点;统一使用px，不直接获取坐标点
        const aMapLocation = this.getCoordinates(e);
        //选中组件拖拽事件
        if (this.mouseStatus == 0) {
          //轨迹线绘制事件（节点移动）
          if (JSON.stringify(this.formData.selectMapComponent) != '{}') {
            if (
              this.formData.selectMapComponent.type ==
                'pulseLineLayoutComponents' &&
              this.$store.state.currentSelectMapToolBar.componentType ==
                'pulseLineLayoutComponents'
            ) {
              console.log('绘制线');
              var selectPlusLineComponent = this.formData.selectMapComponent;
              const pixelVal = e.pixel;
              const coordinates = this.getCoordinates(e);
              const len =
                selectPlusLineComponent.sourceData.features[0].geometry
                  .coordinates.length;
              selectPlusLineComponent.x = pixelVal.x;
              selectPlusLineComponent.y = pixelVal.y;
              selectPlusLineComponent.sourceData.features[0].geometry.coordinates[
                len - 1
              ] = [coordinates.lng, coordinates.lat];
            }
            return;
          }
          return;
        }
        //面图层不做快捷键好移动处理
        if (
          JSON.stringify(this.formData.selectMapComponent) != '{}' &&
          this.formData.selectMapComponent.type != 'polygonComponents'
        ) {
          this.mouseStatus == 1
            ? (this.aMapData.dragEnable = false)
            : (this.aMapData.dragEnable = true);
          this[`${this.formData.selectMapComponent.type}Move`](
            e.pixel.x,
            e.pixel.y,
            aMapLocation
          );
          this.aMapData.keyboardEnable = false; //取消地图键盘事件
        }
      });
    },
    /**
     * 贴图组件移动
     * @param {*} pixelX  x像素点
     * @param {*} pixelY  y像素点
     * @param {*} aMapLocation 坐标点
     */
    scatterLayerComponentsMove(pixelX, pixelY, aMapLocation) {
      const coordinates = [aMapLocation.lng, aMapLocation.lat];
      //获取组件是否绑定mark
      let markComponent =
        this.mapComponents.localLayer.zMarkerLayerComponents.filter((item) => {
          return (
            this.formData.selectMapComponent.componentsId == item.componentsId
          );
        });
      this.formData.selectMapComponent.x = pixelX;
      this.formData.selectMapComponent.y = pixelY;
      this.formData.selectMapComponent.sourceData.features[0].geometry.coordinates =
        coordinates;
      markComponent.length > 0
        ? (markComponent[0].sourceData.features[0].geometry.coordinates =
            coordinates)
        : '';
    },
    //轨迹线组件移动
    pulseLineLayoutComponentsMove(pixelX, pixelY, aMapLocation) {
      let selectMapComponent = this.formData.selectMapComponent;
      //记录x、y坐标
      selectMapComponent.x = pixelX;
      selectMapComponent.y = pixelY;
      //更新对应坐标点
      const coordinates = [aMapLocation.lng, aMapLocation.lat];
      selectMapComponent.sourceData.features[0].geometry.coordinates[
        selectMapComponent.index
      ] = coordinates;
    },
    mouseWheel(e) {
      //获取当前选中组件
      let selectMapComponent = this.formData.selectMapComponent;
      //面图层不做快捷键好移动处理
      if (
        JSON.stringify(selectMapComponent) == '{}' ||
        selectMapComponent.type == 'polygonComponents'
      ) {
        this.aMapData.scrollWheel = true;
        return;
      }
      //取消地图组件的鼠标滚轮
      this.aMapData.scrollWheel = false;
      e.preventDefault();
      const componentSize = e.deltaY < 0 ? 5 : -5;
      this[`${selectMapComponent.type}Wheel`](
        selectMapComponent,
        componentSize
      );
    },
    //贴图组件鼠标滚轮控制
    scatterLayerComponentsWheel(component, componentSize) {
      //判断滚轮方向 -100是往上滑 100是下滑
      component.layerStyle.size[0] += componentSize;
      component.layerStyle.size[1] += componentSize;
      //最小尺寸为5
      if (component.layerStyle.size[1] < 5) {
        component.layerStyle.size[0] = 5;
        component.layerStyle.size[1] = 5;
      }
    },
    //轨迹线鼠标控制
    pulseLineLayoutComponentsWheel(component, componentSize) {
      component.layerStyle.lineWidth += componentSize;
      //最小宽度为5
      if (component.layerStyle.lineWidth < 5) {
        component.layerStyle.lineWidth = 5;
      }
    },
    //鼠标右键操作
    rightMenuEvent(item) {
      if (!item.enable) return;
      let selectMapComponent = this.formData.selectMapComponent;
      switch (item.type) {
        case 'copy':
          let copyMapComponent = JSON.parse(JSON.stringify(selectMapComponent));
          let markComponent = JSON.parse(
            JSON.stringify(
              this.mapComponents.localLayer.zMarkerLayerComponents.filter(
                (item) => {
                  return item.componentsId == selectMapComponent.componentsId;
                }
              )
            )
          );
          //组件复制;这里有同一个组件复制多层重叠问题，可以考虑随机数
          copyMapComponent.x = copyMapComponent.x + 30;
          copyMapComponent.y = copyMapComponent.y + 20;
          const coordinates = pixelSwapToLanLat(
            copyMapComponent.x,
            copyMapComponent.y,
            this.map
          );
          const name = copyMapComponent.sourceData.features[0].properties.name;

          copyMapComponent.sourceData.features[0].geometry.coordinates =
            coordinates; //坐标
          copyMapComponent.zIndex =
            this.mapComponents.localLayer[copyMapComponent.type].length + 12; //层级
          copyMapComponent.sourceData.features[0].properties.name =
            name.indexOf('_copy') > -1
              ? name +
                this.mapComponents.localLayer[copyMapComponent.type].length
              : name +
                '_copy' +
                this.mapComponents.localLayer[copyMapComponent.type].length; //名称
          copyMapComponent.sourceData.features[0].properties.arrIndex =
            this.mapComponents.localLayer[copyMapComponent.type].length; //索引
          copyMapComponent.sourceData.features[0].properties.componentsId =
            this.$UCore.GenUUid(); //id
          this.mapComponents.localLayer[copyMapComponent.type].push(
            copyMapComponent
          );
          //mark层复制
          if (markComponent.length > 0) {
            const name =
              markComponent[0].sourceData.features[0].properties.name;
            const len =
              this.mapComponents.localLayer.zMarkerLayerComponents.length;
            let copyMarkComponent = {
              componentsId: copyMapComponent.componentsId,
              visible: markComponent[0].visible, //是否显示
              opacity: 1, //透明度
              zIndex: len + 1,
              //数据配置
              sourceData: {
                type: 'FeatureCollection',
                features: [
                  {
                    type: 'Feature',
                    geometry: {
                      type: 'Point',
                      coordinates: [coordinates.lng, coordinates.lat],
                    },
                    //自定义数据
                    properties: {
                      componentsId: copyMapComponent.componentsId, //关联id
                      name:
                        name.indexOf('_copy') > -1
                          ? name + len
                          : name + '_copy' + len, //文本内容
                      val: 500, //数值内容
                    },
                  },
                ],
              },
              //样式配置
              layerStyle: {
                unit: 'meter', //默认为地理单位，可选值px
                alwaysFront: true, //是否锁定视角
                size: copyMapComponent.layerStyle.size, //默认宽高为组件宽高
                rotation: 0, //旋转角度
                //自定义文本内容
                content: (index, feat) => {
                  const props = feat.properties;
                  const leftColor = 'rgba(0, 28, 52, 0.6)';
                  const rightColor = '#038684';
                  const borderColor = '#038684';
                  return `${
                    '<div style="width: 490px; height: 228px; padding: 0 0;">' +
                    '<p style="display: block; height:80px; line-height:80px;font-size:40px;background-image: linear-gradient(to right, '
                  }${leftColor},${leftColor},${rightColor},rgba(0,0,0,0.4)); border:4px solid ${borderColor}; color:#fff; border-radius: 15px; text-align:center; margin:0; padding:5px;">${
                    props['name']
                  }: ${
                    props['val']
                  }</p><span style="width: 130px; height: 130px; margin: 0 auto; display: block; background: url(https://a.amap.com/Loca/static/loca-v2/demos/images/prism_${'blue'}.png);"></span></div>`;
                },
              },
            };
            this.mapComponents.localLayer.zMarkerLayerComponents.push(
              copyMarkComponent
            );
          }
          break;
        case 'delete':
          this[`delete${selectMapComponent.type}`](selectMapComponent);
          break;
        case 'nextTop':
          selectMapComponent.zIndex++;
          break;
        case 'nextBottom':
          selectMapComponent.zIndex--;
          break;
      }
      this.displayContextmenu = false;
    },
    //---------------------------删除操作------------------------------/
    //贴图点删除
    deletescatterLayerComponents(selectMapComponent) {
      const markComponent =
        this.mapComponents.localLayer.zMarkerLayerComponents.filter(
          (item, index) => {
            item.deleteIndex = index;
            return selectMapComponent.componentsId == item.componentsId;
          }
        );
      if (markComponent.length > 0) {
        //delete mark
        this.mapComponents.localLayer.zMarkerLayerComponents.splice(
          markComponent[0].deleteIndex,
          1
        );
      }
      //delete scatterLayer
      this.mapComponents.localLayer[selectMapComponent.type].splice(
        selectMapComponent.arrIndex,
        1
      );
      this.clickMap();
    },
    //线图层删除
    deletepulseLineLayoutComponents(selectMapComponent) {
      const markComponent =
        this.mapComponents.localLayer.zMarkerLayerComponents.filter(
          (item, index) => {
            item.deleteIndex = index;
            return selectMapComponent.componentsId == item.componentsId;
          }
        );
      if (markComponent.length > 0) {
        //delete mark
        this.mapComponents.localLayer.zMarkerLayerComponents.splice(
          markComponent[0].deleteIndex,
          1
        );
      }
      this.mapComponents.localLayer[selectMapComponent.type].splice(
        selectMapComponent.arrIndex,
        1
      );
      this.formData.selectMapComponent = {};
    },
    //面图层删除
    deletepolygonComponents(selectMapComponent) {
      let buildings = this.searchBuilding(
        selectMapComponent.sourceData.features[0].properties.componentsId
      );
      //删除3D建筑物图层掩模
      this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas.splice(
        buildings.arrIndex,
        1
      );
      //修复长度为0是全部为空
      this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas
        .length == 0
        ? (this.mapComponents.normalLayer.elAmapLayerBuildings.styleOpts.areas =
            null)
        : '';
      //删除面图层
      this.mapComponents.localLayer[selectMapComponent.type].splice(
        selectMapComponent.arrIndex,
        1
      );
      this.clickMap();
    },
    //---------------------------------------------------------------/
  },
};
</script>
<style lang="less" scoped>
.leftIcon {
  position: fixed;
  top: 50%;
  color: white;
  height: 88px;
  z-index: 999;
  background: #15a3fa;
  line-height: 88px;
  border-radius: 0px 5px 5px 0px;
}

.leftIcon:hover {
  cursor: pointer;
}

.rightIcon {
  position: fixed;
  top: 50%;
  color: white;
  height: 88px;
  z-index: 999;
  background: #15a3fa;
  line-height: 88px;
  border-radius: 5px 0px 0px 5px;
}

.rightIcon:hover {
  cursor: pointer;
}

/deep/ .vc-color-wrap {
  width: 160px;
}

#components-layout .ant-layout-sider {
  background: #fff;
  color: rgb(167, 164, 164);
}

.mapSlide {
  min-height: 524px;
  overflow: auto;
}

.gaodeMap {
  width: 100%;
  height: 100%;
  position: relative;

  .contextMenu {
    position: absolute;
    z-index: 99999;
    background: #ffffff;
    padding: 5px 0;
    margin: 0px;
    display: block;
    border-radius: 5px;
    box-shadow: 2px 5px 10px rgba(0, 0, 0, 0.3);

    li {
      list-style: none;
      padding: 0px;
      margin: 0px;

      p {
        text-decoration: none;
        display: block;
        padding: 0px 15px 1px 20px;
        margin: 0;
        user-select: none;
        -webkit-user-select: none;

        .shortcut {
          width: 115px;
          text-align: right;
          float: right;
        }
      }

      p:hover {
        background-color: #0cf;
        color: #ffffff;
        cursor: default;
      }

      .disabled {
        color: #999;
      }

      .disabled:hover {
        color: #999;
        background-color: transparent;
      }
    }

    li.separator {
      border-top: solid 1px #e3e3e3;
      padding-top: 5px;
      margin-top: 5px;
    }
  }
}
</style>
